/**
 * 
 */
package com.cmpanyandi.elearning.wordsdriller.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.cmpanyandi.elearning.utils.db.DbAdapter;
import com.cmpanyandi.elearning.wordsdriller.model.Dictionary;

/**
 * Dictionary edit form.
 * 
 * @author wojtek
 * 
 */
public class DictionaryEdit extends DictionaryActivityForm {

    private EditText nameText;
    private EditText descriptionText;
    private ImageView save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	setContentView(R.layout.dictionary_edit);
	super.onCreate(savedInstanceState);
	nameText = (EditText) findViewById(R.id.name);
	descriptionText = (EditText) findViewById(R.id.description);
	
	populateFields();
	setLabel();
	save = (ImageView) findViewById(R.id.mainSave);
	save.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View view) {
		setResult(RESULT_OK);
		pk = Long.valueOf(0);
		saveState();
		finish();
	    }

	});
	
	
    }
    
    private void setLabel() {
	if (pk == unsavedPk) {
	    mainDescription.setText(R.string.dictionary_create_new);
	} else {
	    mainDescription.setText(R.string.dictionary_edit);
	}
    }
    private void populateFields() {

	if (pk != null && pk.longValue() > 0) {
	    Dictionary dictionary = (Dictionary) DbAdapter.getInstance().getByPK(new Dictionary(pk));
	    pk = dictionary.getPk();
	    nameText.setText(dictionary.getName());
	    descriptionText.setText(dictionary.getDescription());
	}
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
	super.onSaveInstanceState(outState);
	outState.putLong(getStateProperty(), pk);
    }


    @Override
    protected void onResume() {
	super.onResume();
	populateFields();
    }

    private void saveState() {
	if (pk != null && pk.longValue() >= 0) {
	    Dictionary dict = new Dictionary(pk);
	    dict.setName(nameText.getText().toString());
	    dict.setDescription(descriptionText.getText().toString());
	    DbAdapter.getInstance().saveOrUpdate(dict);
	    pk = dict.getPk();
	}
    }

    @Override
    protected String getStateProperty() {
	return "state_dictionary";
    }

}
